﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp.View.LineManage
{
    /// <summary>
    /// UC_StationManage.xaml 的交互逻辑
    /// </summary>
    public partial class UC_StationManage : UserControl
    {
        public UC_StationManage()
        {
            InitializeComponent();
        }
        DataTable dtStationManage;
        BLL.UCStationManage.UC_StationManageClient myStationManage = new BLL.UCStationManage.UC_StationManageClient();
        BLL.PublicFunction.PublicFunctionClient myPublicFunction = new BLL.PublicFunction.PublicFunctionClient();

        #region 分页参数
        string strGetFields = "ROW_NUMBER () OVER (ORDER BY S_Site.siteID DESC) AS number,S_Site.siteID,RTRIM(S_Site.siteName) AS siteName,RTRIM(S_Site.shortCode) AS shortCode,RTRIM(S_Site.fullCode) AS fullCode,S_Site.proID,RTRIM(D_Province.proName) AS proName,RTRIM(CASE WHEN S_Site.stopOrNot='true' THEN '停用' ELSE '未停用' END) AS stopOrNot";
        string strTblName = " S_Site INNER JOIN D_Province ON S_Site.proID = D_Province.proID";
        string strFldName = "siteID";//排序的字段名
        int intPageSize = 20;//页尺寸（显示条数）
        int intPageIndex = 1;//页码
        string strWhere = "1=1";//查询条件 (注意: 不要加 where)
        decimal decPageCount = 0;//页数
        #endregion

        /// <summary>
        /// 加载时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            #region 按钮操控
            btnStop.IsEnabled = false;//禁用停用按钮
            btnStop.Opacity = 0.5;
            btnDelete.IsEnabled = false;//禁用删除按钮
            btnDelete.Opacity = 0.5;
            btnUpdate.IsEnabled = false;//禁用修改按钮
            btnUpdate.Opacity = 0.5;
            #endregion
            #region 初始化窗体数据
            txtCurrentPage.Text = "0";//当前页数
            lblMaxPage.Content = decPageCount;//最大页数
            int[] intPageLineCounts = { 5, 10, 20, 30, 50, 100, 150 };//创建int数组
            cboPageLineCount.ItemsSource = intPageLineCounts;//绑定每页行数下拉框
            cboPageLineCount.Text = intPageSize.ToString();//设置默认值
            GetTable();
            #endregion

        }
        /// <summary>
        /// 刷新表格
        /// </summary>
        public void GetTable()
        {
            //接收表格
            dtStationManage = myStationManage.SelectStationManage().Tables[0];
            //绑定数据源
            dgStationManage.ItemsSource = dtStationManage.DefaultView;

        }
        #region 分页封装
        /// <param name="intPageLineCount">条数</param>
        /// <param name="intCurrentPage">当前页</param>
        /// <param name="bolSeleteSum">返回记录总数</param>
        /// <param name="bolInvertedOrder">设置排序类型</param>
        /// <returns></returns>
        public DataTable SelectDataByPage(int intPageLineCount, int intCurrentPage, bool bolSeleteSum, bool bolInvertedOrder)
        {
            if (txt_station.Text.Trim() != "")
            {
                //累加模糊查询内容
                strWhere = "siteName like '%'+'" + txt_station.Text.Trim() + "'+'%'";
            }
            if (txt_pro.Text.Trim() != "")
            {
                //累加模糊查询内容
                strWhere = strWhere + "and proName like '%" + txt_pro.Text.Trim() + "%'";
            }else if((txt_station.Text == "" || txt_station.Text == string.Empty) && (txt_pro.Text.Trim() == "" || txt_station.Text.Trim() == string.Empty))
            {
                //默认查询内容
                strWhere = "1=1";
            }
            //获取数据总行数(//获取查询结果的行数)
            decPageCount = Convert.ToDecimal(myPublicFunction.PublicPagingSelect(strTblName, strGetFields, strFldName, intPageSize, intPageIndex, true, true, strWhere).Tables[0].Rows[0][0]);
            //页数的判断有多少页 （总行数/条数）
            if (decPageCount / intPageLineCount <= Convert.ToInt32(decPageCount / intPageLineCount))
            {
                //页数赋值(默认decPageCount = 0)
                decPageCount = Convert.ToInt32(decPageCount / intPageLineCount);
            }
            else
            {
                //页数（默认decPageCount = 0） +1
                decPageCount = Convert.ToInt32(decPageCount / intPageLineCount) + 1;
            }
            //如果当前页数大于最大页数，则重新赋值为最大页数（当前页 >总页数）
            if (intCurrentPage > decPageCount)
            {
                intPageIndex = (int)decPageCount;
                intCurrentPage = (int)decPageCount;
            }
            //如果当前页数为0，则重新赋值为1
            if (intPageIndex == 0 || intCurrentPage == 0)
            {
                intPageIndex = 1;
                intCurrentPage = 1;
            }
            lblMaxPage.Content = decPageCount.ToString();//给最大页数赋值
            txtCurrentPage.Text = intCurrentPage.ToString();//给当前页数文本框赋值
            //执行分页得到具体的data数据(//返回查询出来的结果)
            return myPublicFunction.PublicPagingSelect(strTblName, strGetFields, strFldName, intPageSize, intPageIndex, bolSeleteSum, bolInvertedOrder, strWhere).Tables[0];
        }
        /// <summary>
        /// 控制按钮禁用和启用
        /// </summary>
        public void UpdatePagingButton()
        {
            //如果是首页，则把上一页和首页按钮禁用(样式)
            if (Convert.ToInt32(txtCurrentPage.Text) <= 1)
            {
                //禁用（首页，上一页）按钮
                imgMostUp.Opacity = 0.3;
                imgMostUp.Cursor = Cursors.Arrow;
                imgUp.Opacity = 0.3;
                imgUp.Cursor = Cursors.Arrow;
            }
            else
            {
                //启用（首页，上一页）按钮
                imgMostUp.Opacity = 1;
                imgMostUp.Cursor = Cursors.Hand;
                imgUp.Opacity = 1;
                imgUp.Cursor = Cursors.Hand;
            }
            //如果是尾页，则把下一页和尾页按钮禁用(样式)
            if (Convert.ToInt32(txtCurrentPage.Text) >= Convert.ToInt32(lblMaxPage.Content))
            {
                //禁用（末尾页，下一页）按钮
                imgMostDown.Opacity = 0.3;
                imgMostDown.Cursor = Cursors.Arrow;
                imgDown.Opacity = 0.3;
                imgDown.Cursor = Cursors.Arrow;
            }
            else
            {
                //启用（末尾页，下一页）按钮
                imgMostDown.Opacity = 1;
                imgMostDown.Cursor = Cursors.Hand;
                imgDown.Opacity = 1;
                imgDown.Cursor = Cursors.Hand;
            }

        }
        #endregion
        /// <summary>
        /// 查询按钮（条件查询）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Select_Click(object sender, RoutedEventArgs e)
        {
            //调用查询方法，把返回的值，赋给DGV
            dtStationManage = SelectDataByPage(intPageSize, intPageIndex, false, true);
            //绑定数据
            dgStationManage.ItemsSource = dtStationManage.AsDataView();
            //数据<1 (无数据)
            if (dtStationManage.Rows.Count < 1)
            {
                //恢复成默认
                intPageIndex = 0;
                txtCurrentPage.Text = "0";
                cboPageLineCount.IsEnabled = false; //禁用每页行数下拉框
                txtCurrentPage.IsEnabled = false;//禁用当前页文本框
            }
            else
            {
                cboPageLineCount.IsEnabled = true;
                txtCurrentPage.IsEnabled = true;
            }
            UpdatePagingButton();
        }
        /// <summary>
        /// 首页按钮（鼠标左键按下事件）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void imgMostUp_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //首页
            if (((Image)sender).Opacity == 1)
            {
                intPageIndex = 1;//当前显示页:第一页
                txtCurrentPage.Text = "1";//首页
                btn_Select_Click(null, null);
            }
        }
        /// <summary>
        /// 上一页按钮（鼠标左键按下事件）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void imgUp_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //上一页
            if (((Image)sender).Opacity == 1)
            {
                intPageIndex--;//上一页：索引-1
                txtCurrentPage.Text = intPageIndex.ToString();//设置文本值显示当前页
                btn_Select_Click(null, null);
            }

        }
        /// <summary>
        /// 下一页按钮（鼠标左键按下事件）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void imgDown_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //下一页
            if (((Image)sender).Opacity == 1)
            {
                intPageIndex++;//下一页：当前索引+1
                txtCurrentPage.Text = intPageIndex.ToString();//当前页
                btn_Select_Click(null, null);
            }
        }
        /// <summary>
        /// 尾页按钮（鼠标左键按下事件）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void imgMostDown_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //尾页
            if (((Image)sender).Opacity == 1)
            {
                intPageIndex = Convert.ToInt32(lblMaxPage.Content);//获取最大页数
                txtCurrentPage.Text = intPageIndex.ToString();//当前页
                //触发事件
                btn_Select_Click(null, null);
            }
        }
        /// <summary>
        /// 自定义跳转页（文本改变事件）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtCurrentPage_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                //屏蔽中文输入和非法字符粘贴 %#@$@#输入
                TextBox textBox = sender as TextBox;
                TextChange[] change = new TextChange[e.Changes.Count];
                e.Changes.CopyTo(change, 0);
                int offset = change[0].Offset;
                //有输入内容
                if (change[0].AddedLength > 0)
                {
                    int num = 0;
                    //判断
                    if(!int.TryParse(textBox.Text, out num)){
                        textBox.Text = textBox.Text.Remove(offset, change[0].AddedLength).ToString().Trim();
                        textBox.Select(offset, 0);
                    }
                }
                if (decPageCount != 0)
                {
                    //判断输入数字>总页数
                    if (Convert.ToInt32(textBox.Text.Trim()) > decPageCount)
                    {
                        //获取=总页数
                        textBox.Text = decPageCount.ToString();
                    } 
                    else if (Convert.ToInt32(textBox.Text.Trim())<1)//输入数字<1
                    {
                        textBox.Text = "1";
                    }
                }
                //当前输入的值！=现在的页数
                if (intPageIndex != Convert.ToInt32(textBox.Text.Trim()) && Convert.ToInt32(textBox.Text.Trim()) >= 1)
                {
                    //执行分页
                    intPageIndex = Convert.ToInt32(textBox.Text.Trim());
                    btn_Select_Click(null, null);
                }

            }
            catch (Exception)
            {
                btn_Select_Click(null, null);
            }
        }
        /// <summary>
        /// 条数下拉框改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cboPageLineCount_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //每页行数
            intPageSize = Convert.ToInt32(cboPageLineCount.SelectedValue);
            intPageIndex = 1;
            //触发分页
            btn_Select_Click(null, null);
        }
        /// <summary>
        /// 站点选中列改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgStationManage_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {
            try
            {
                if (((DataRowView)dgStationManage.SelectedItem) != null)//判断选中的行是否为空
                {
                    //控制按钮（修 改、删除、停用）
                    //激活停用按钮
                    btnStop.IsEnabled = true;
                    btnStop.Opacity = 1;
                    btnDelete.IsEnabled = true;
                    btnDelete.Opacity = 1;
                    btnUpdate.IsEnabled = true;
                    btnUpdate.Opacity = 1;

                    //绑定邻居站点表（获取主键ID）
                    int intSiteID = Convert.ToInt32(((DataRowView)dgStationManage.CurrentItem).Row["siteID"]);
                    #region 绑定站点信息
                    DataTable dtsite = myStationManage.SelectSiteBySiteId(intSiteID).Tables[0];
                    dgSite.ItemsSource = dtsite.DefaultView;
                    #endregion
                }
                else
                {
                    //禁用停用按钮
                    btnStop.IsEnabled = false;
                    btnStop.Opacity = 0.5;
                    btnUpdate.IsEnabled = false;
                    btnUpdate.Opacity = 0.5;
                    btnDelete.IsEnabled = false;
                    btnDelete.Opacity = 0.5;
                }


            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return;
            }
        }
        /// <summary>
        /// 打开新增窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Insert_Click(object sender, RoutedEventArgs e)
        {
            //实例化窗口
            WD_InsertStationManage my = new WD_InsertStationManage();
            my.ShowDialog();
            GetTable();//刷新页面(绑定站点信息)
        }
        /// <summary>
        /// 打开修改窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Update_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //获取选中行
                if ((DataRowView)dgStationManage.SelectedItem != null)
                {
                    DataRowView dataRow = (DataRowView)dgStationManage.SelectedItem;
                    WD_UpdateStationManage myUpdate = new WD_UpdateStationManage(dataRow);
                    myUpdate.ShowDialog();
                    GetTable();
                }
                else
                {
                    MessageBox.Show("请选择要修改的站点信息！");
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Delete_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if ((DataRowView)dgStationManage.SelectedItem != null)
                {
                    int intDsum = 0;//记录删除成功条数
                    //判断是否选中数据
                    MessageBoxResult dr = MessageBox.Show("是否删除？", "系统提示", MessageBoxButton.OKCancel, MessageBoxImage.Question);
                    //弹出确定对话框
                    if (dr == MessageBoxResult.OK)
                    {
                        int intSiteID = Convert.ToInt32(((DataRowView)dgStationManage.SelectedItem).Row["siteID"]);//站点逐渐ID
                        //1.删除单条数据(站点信息)
                        int intSiteCount = myStationManage.DeleteStation(intSiteID);
                        //（站点表）删除成功
                        if (intSiteCount > 0)
                        {
                            //2、批量删除当前站点相关的邻居站点数据
                            for (int i = 0; i < dgSite.Items.Count; i++)
                            {
                                intDsum++;
                                //获取主键ID
                                int intNeighborSiteId = Convert.ToInt32(((DataRowView)dgSite.Items[i]).Row["siteNeighborID"]);
                                int intNeighborCount = myStationManage.DeleteNeighborSite(intNeighborSiteId);
                            }
                        }
                        //删除行数相同
                        if (intDsum == dgSite.Items.Count)
                        {
                            MessageBox.Show("删除站点成功！", "系统提示", MessageBoxButton.OKCancel, MessageBoxImage.Information);
                        }
                    }
                    //调用绑定表格方法
                    GetTable();//刷新页面
                }
                else
                {
                    MessageBox.Show("请选择要删除的数据！", "系统提示", MessageBoxButton.OKCancel, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return;
            }
        }
        /// <summary>
        /// 停用按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Stop_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                MessageBoxResult dr = MessageBox.Show("一旦停用站点就不能启用了，确定吗？", "系统提示", MessageBoxButton.OKCancel, MessageBoxImage.Question);
                //弹出确定对话框  
                if (dr == MessageBoxResult.OK)//如果点了确定按钮
                {
                    if ((DataRowView)dgStationManage.SelectedItem != null)
                    {
                        int intSiteID = Convert.ToInt32(((DataRowView)dgStationManage.SelectedItem).Row["siteID"]);
                        int intCount = myStationManage.StopSite(intSiteID);//停用
                        if (intCount > 0)
                        {
                            MessageBox.Show("停用成功！", "系统提示", MessageBoxButton.OKCancel, MessageBoxImage.Information);
                            //调用绑定表格方法
                            GetTable();//刷新页面
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        
    }
}
